package com.luoke.util.myjdbc.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.luoke.util.myjdbc.SFunction;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class DBUtil<T> {

    private static Map<Class, SerializedLambda> CLASS_LAMBDA_CACHE = new ConcurrentHashMap<>();
    public static<T> String getFieldName(SFunction<T> fn) {
        SerializedLambda lambda = getSerializedLambda(fn);
        // 获取方法名
        String methodName = lambda.getImplMethodName();
        String prefix = null;
        if (methodName.startsWith("get")) {
            prefix = "get";
        } else if (methodName.startsWith("is")) {
            prefix = "is";
        }
        if (prefix == null) {
            StaticLog.error("无效的getter方法: " + methodName);
        }
        // 截s取get/i之后的字符串并转换首字母为小写
        String underlineCase = StrUtil.toUnderlineCase(methodName.replace(prefix, ""));
        return underlineCase;
//        return toLowerCaseFirstOne(methodName.replace(prefix, ""));
    }

    /**
     * 关键在于这个方法
     */
    public static SerializedLambda getSerializedLambda(Serializable fn) {
        SerializedLambda lambda = CLASS_LAMBDA_CACHE.get(fn.getClass());
        // 先检查缓存中是否已存在
        if (lambda == null) {
            try {
                // 提取SerializedLambda并缓存
                Method method = fn.getClass().getDeclaredMethod("writeReplace");
                method.setAccessible(Boolean.TRUE);
                lambda = (SerializedLambda) method.invoke(fn);
                CLASS_LAMBDA_CACHE.put(fn.getClass(), lambda);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return lambda;
    }

    public static <T> String getTableName(Class<T> clazz) {
        String simpleName = clazz.getSimpleName();
        String tableName = StrUtil.toUnderlineCase(simpleName);//转成下划线
        if (tableName.equals("order")) {
            tableName = "`" + tableName + "`";
        }
        return tableName;
    }
}
